import 'dart:convert';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mmkv/mmkv.dart';

import '../../../utils/navigation_util.dart';
import '../../video_tag/entity/video_bean.dart';
import '../intent/video_list_state.dart';

class VideoListViewModel extends StateNotifier<VideoListState> {
  VideoListViewModel() : super(VideoListState());

  Future<void> initData(String json) async {
    String? mJson = MMKV.defaultMMKV().decodeString(json);
    if (mJson == null || mJson.isEmpty) {
    } else {
      List<VideoBean> asyncVideoList = await parseVideoListAsync(mJson);
      mJson = "";
      state = state.copyWith(uiList: asyncVideoList);
    }
  }

  // 方法1: 基础转换函数
  List<VideoBean> parseVideoList(String jsonString) {
    // 解析JSON字符串为List<dynamic>
    List<dynamic> jsonList = jsonDecode(jsonString);

    // 将每个Map转换为VideoItem对象
    List<VideoBean> videoList = jsonList.map((jsonItem) => VideoBean.fromJson(jsonItem as Map<String, dynamic>)).toList();

    return videoList;
  }

  // 方法3: 异步转换（适合大数据量）
  Future<List<VideoBean>> parseVideoListAsync(String jsonString) async {
    return Future.delayed(Duration(milliseconds: 100), () {
      return parseVideoList(jsonString);
    });
  }
  void goNextPage(String videoName, String videoUrl) {
    navigationUtil.goVideoPlayPage(videoName,videoUrl);
  }
}
